<template>
  <div class="login">
    <!-- 登录/注册tab页切换 -->
    <div class="login-container">
      <ul class="menu-tab">
        <li
          v-for="value in MenuData"
          :key="value.type"
          @click="clickMenu(value)"
          :class="{ current: value.current }"
        >
          {{ value.txt }}
        </li>
      </ul>
    </div>
    <!-- 登录/注册tab页切换 -->
    <!-- form表单部分 -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      class="demo-ruleForm"
    >
      <el-form-item prop="userName">
        <label>用户名</label>
        <el-input
          v-model="ruleForm.userName"
          placeholder="请输入邮箱作为用户名"
          type="text"
          autocomplete="off"
          clearable
        />
      </el-form-item>

      <el-form-item prop="password">
        <label>密码</label>
        <el-input
          v-model="ruleForm.password"
          placeholder="请输入密码"
          type="password"
          autocomplete="off"
          minlength="8"
          maxlength="16"
          clearable
          show-password
        />
        <!-- 限制输入长度为8~16个字符 -->
      </el-form-item>

      <el-form-item prop="checkPass" v-show="model === 'register'">
        <label>重复密码</label>
        <el-input
          v-model="ruleForm.checkPass"
          placeholder="请重复输入的密码"
          type="password"
          autocomplete="off"
          minlength="8"
          maxlength="16"
          clearable
          show-password
        />
        <!-- 限制输入长度为8~16个字符 -->
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="btnbool"
          type="primary"
          @click="submitForm(ruleFormRef)"
          class="login-btn block"
          >{{ model === "login" ? "登录" : "注册" }}</el-button
        >
        <!-- <el-button @click="resetForm(ruleFormRef)">Reset</el-button> -->
      </el-form-item>
    </el-form>
    <!-- form表单部分 -->
  </div>
</template>

<script lang="ts" setup>
// 引入element-plus表单，reactive用以创建复杂数据类型
import { reactive, ref, onMounted, watch } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
// 引入element-plus表单
// 引入正则验证工具库
import * as check from "@/utils/regtools";
// 引入正则验证工具库
// 引入link请求数据
import link from "@/api/link";
// 引入link请求数据
// 引入请求地址
import apiUrl from "@/api/url";
// 引入请求地址
// 引入md5加密的hooks函数
import useMd5 from "@/hooks/hooksIndex";
// 引入md5加密的hooks函数
// 引入vue-router
import { useRouter } from "vue-router";
// 引入vue-router
const router = useRouter();
// 创建复杂数据类型
const MenuData = reactive([
  { txt: "登录", current: true, type: "login" },
  { txt: "注册", current: false, type: "register" },
]);

const model = ref("login");

onMounted(() => {
  console.log(process.env.VUE_APP_API);
  // ElMessage("注册成功");
});

let clickMenu = (item: any) => {
  MenuData.forEach((elem) => {
    elem.current = false;
  });
  item.current = true;

  // 修改保存点击的状态
  model.value = item.type;
};
// 创建复杂数据类型

// element-plus表单
const ruleFormRef = ref<FormInstance>();

const checkUser = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("用户名不得为空！"));
  } else if (check.checkUser(value)) {
    return callback(new Error("用户名格式不正确！"));
  } else {
    callback();
  }
  // setTimeout(() => {
  //   if (!Number.isInteger(value)) {
  //     callback(new Error("Please input digits"));
  //   } else {
  //     if (value < 18) {
  //       callback(new Error("Age must be greater than 18"));
  //     } else {
  //       callback();
  //     }
  //   }
  // }, 1000);
};

const validatePass = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("密码不得为空！"));
  } else if (check.checkPass(value)) {
    callback(
      new Error(
        "最少8个最多16个字符，至少1个大写字母，1个小写字母，1个数字和1个特殊字符!"
      )
    );
  } else {
    callback();
  }
  // else {
  //   if (ruleForm.checkPass !== "") {
  //     if (!ruleFormRef.value) return;
  //     ruleFormRef.value.validateField("checkPass", () => null);
  //   }
  //   callback();
  // }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  // 在登陆页面取消重复密码的校验
  if (model.value === "login") {
    callback();
  }
  if (value === "") {
    callback(new Error("请再输入一次密码！"));
  } else if (value !== ruleForm.password) {
    callback(new Error("与先前的输入不一致！"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  userName: "",
  password: "",
  checkPass: "",
});

let btnbool = ref(true);
watch(ruleForm, (newValue, oldValue) => {
  // console.log(newValue, oldValue);
  if (model.value === "login") {
    !newValue.userName || !newValue.password
      ? (btnbool.value = true)
      : (btnbool.value = false);
  } else {
    !newValue.userName || !newValue.password || !newValue.checkPass
      ? (btnbool.value = true)
      : (btnbool.value = false);
  }
});

// 定义以何种方式触发表单验证
const rules = reactive({
  password: [{ validator: validatePass, trigger: "blur" }],
  checkPass: [{ validator: validatePass2, trigger: "blur" }],
  userName: [{ validator: checkUser, trigger: "blur" }],
});
// 定义以何种方式触发表单验证

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (model.value === "login") {
        console.log("登录");
        link(
          apiUrl.register,
          "GET",
          {},
          { name: ruleForm.userName, password: useMd5(ruleForm.password) }
          //password: i6g9!3M#yVnsTFei
        ).then((resolve: any) => {
          console.log(resolve);
          if (resolve.data.length != 0) {
            ElMessage({
              message: "登录成功！",
              type: "success",
            });
            router.push("/home");
          } else {
            ElMessage.error("登录失败！请检查账号密码是否有误！");
          }
        });
      } else {
        let data = {
          name: ruleForm.userName,
          password: useMd5(ruleForm.password),
        };
        link(apiUrl.register, "POST", data).then((resolve: any) => {
          console.log(resolve);
          if (Object.keys(resolve.data).length !== 0) {
            console.log("注册成功");
            ElMessage({
              message: "Congrats, 注册成功",
              type: "success",
            });
            model.value = "login";
            MenuData.forEach((v) => {
              v.current = false;
            });
            MenuData[0].current = true;
          } else {
            console.log("注册失败");
          }
        });
      }
      console.log("submit!");
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// element-plus表单
</script>

<style lang="scss">
.login {
  // background-color: #000066;
  background-image: url(@/assets/IMG_00083.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(255, 255, 255, 0.5);
  }
}
.demo-ruleForm {
  width: 30%;
  margin: 50px auto;
  label {
    display: block;
    margin-bottom: 3px;
    font-size: 14px;
    color: #fff;
  }
  .login-btn {
    margin-top: 20px;
  }
  .block {
    display: block;
    width: 100%;
  }
}
</style>
